package elastic

import (
	"context"
	"errors"
	"github.com/olivere/elastic/v7"
	"kuafu/config"
	"kuafu/progress/log"
	"strings"
	"time"
)

type EsClient struct {
	client *elastic.Client
}

func Create(config *config.AppConfig) *EsClient {
	esClient := new(EsClient)

	clientInternal, err := elastic.NewClient(
		elastic.SetURL(strings.Split(config.Es.EsAddr, ",")...),
		elastic.SetErrorLog(log.Log),
		elastic.SetInfoLog(log.Log),
		func(client *elastic.Client) error {
			if config.Es.EsUsername != "" && config.Es.EsPassword != "" {
				err := elastic.SetBasicAuth(config.Es.EsUsername, config.Es.EsPassword)(client)
				return err
			}
			return nil
		},
		elastic.SetHealthcheckTimeout(time.Second*30),
		elastic.SetSniff(config.Es.EsSniff))
	esClient.client = clientInternal

	if err != nil {
		panic(err)
	}
	return esClient
}

func (esClient *EsClient) Exist(indexName string) (bool, error) {
	service := esClient.client.IndexExists(indexName)
	result, err := service.Do(context.Background())
	if err != nil {
		return false, err
	}
	return result, nil
}

func (esClient *EsClient) CreatIndex(indexName string, mapping string) error {
	ctx := context.Background()
	createIndex, err := esClient.client.CreateIndex(indexName).BodyString(mapping).Do(ctx)
	if err != nil {
		return err
	}
	if !createIndex.Acknowledged {
		return errors.New("!createIndex.Acknowledged")
	}
	return nil
}

func (esClient *EsClient) BulkAdd(indexName string, data []string) (bool, error) {
	ctx := context.Background()
	bulkReq := esClient.client.Bulk()
	for _, v := range data {
		req := elastic.NewBulkIndexRequest().
			Index(indexName).
			Doc(v)
		bulkReq = bulkReq.Add(req)
	}
	_, err := bulkReq.Do(ctx)

	if err != nil {
		return false, err
	}
	return true, nil
}
